package com.runfast.waimai.web.controller.business;

import com.google.common.base.Joiner;
import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.MyUtil;
import com.runfast.waimai.utils.StringUtil;
import com.runfast.waimai.utils.TimeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * ${DESCRIPTION}商家管理
 *
 * @author chenzheng
 * @create 2018-05-08 15:55
 **/
@RestController("businessController")
@RequestMapping("/server/business")
public class BusinessController {


    @Autowired
    private RunfastBusinessService runfastBusinessService;
    @Autowired
    private RunfastBusinessAccountsService runfastBusinessAccountsService;
    @Autowired
    private RunfastGoodsSellTypeService runfastGoodsSellTypeService;
    @Autowired
    private RunfastGoodsSellService runfastGoodsSellService;
    @Autowired
    private RunfastBusinessTypeService runfastBusinessTypeService;
    @Autowired
    private RunfastActivityService runfastActivityService;
    @Autowired
    public RunfastBusinessHasTypeService runfastBusinessHasTypeService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;

    /**
     * 商家列表---新增商家的列表
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable, RunfastBusiness business) throws ParseException{

        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        Map<Object,Object> map=new HashMap<Object, Object>();
        List<RunfastBusiness> list=new ArrayList<RunfastBusiness>();
        Integer total=null;
        //已完成的
        //List<RunfastBusiness> doList=new ArrayList<RunfastBusiness>();
        Integer doTotal=null;
        RunfastBusinessExample doExample=new RunfastBusinessExample();
        RunfastBusinessExample.Criteria doExampleCriteria =doExample.createCriteria();
        //待完善
        //List<RunfastBusiness> unDoList=new ArrayList<RunfastBusiness>();
        Integer unDoTotal=null;
        RunfastBusinessExample unDoExample=new RunfastBusinessExample();
        RunfastBusinessExample.Criteria unDoExampleCriteria=unDoExample.createCriteria();
        //近七日
        //List<RunfastBusiness> list7=new ArrayList<RunfastBusiness>();
        Integer total7=null;
        RunfastBusinessExample example7=new RunfastBusinessExample();
        RunfastBusinessExample.Criteria  example7Criteria=example7.createCriteria();
        doExampleCriteria.andUndoneEqualTo(false);
        unDoExampleCriteria.andUndoneEqualTo(true);
        example7Criteria.andCreatetimeBetween(MyUtil.getStartDay( TimeUtil.getDay7()),MyUtil.getEndDay(new Date()));
        doExample.setOrderByClause("createtime  desc");
        unDoExample.setOrderByClause("createtime  desc");
        example7.setOrderByClause("createtime  desc");
        if(StringUtils.isNotBlank(business.getAgentIds())){
            List<String> result = Arrays.asList(StringUtils.split(business.getAgentIds(),","));
            if(result.size()>0){
                List<Integer> in=new ArrayList<Integer>();
                for(String s:result){
                    in.add(StringUtil.stringToInteger(s));
                }
                doExampleCriteria.andAgentidIn(in);
                unDoExampleCriteria.andAgentidIn(in);
                example7Criteria.andAgentidIn(in);
            }
        }
        if(admin!=null && accounts!=null && admin.getType()==3){
            //商家帐号登录----只能看自己家的
            doExampleCriteria.andIdEqualTo(accounts.getBusinessid());
            unDoExampleCriteria.andIdEqualTo(accounts.getBusinessid());
            example7Criteria.andIdEqualTo(accounts.getBusinessid());

        }else if(admin!=null && agentAccounts!=null && admin.getType()==2){
            List<Integer> agents=agentAccounts.getAgents();//代理商所管的代理商ids
            doExampleCriteria.andAgentidIn(agents);
            unDoExampleCriteria.andAgentidIn(agents);
            example7Criteria.andAgentidIn(agents);
        }else if(admin !=null && admin.getType()==1){
            //后台管理员---查看全部的
            if(admin.getAgents().size()>0){
                doExampleCriteria.andAgentidIn(admin.getAgents());
                unDoExampleCriteria.andAgentidIn(admin.getAgents());
                example7Criteria.andAgentidIn(admin.getAgents());
            }else{
                //doExample=null;
                //unDoExample=null;
                //example7=null;
            }
        }
        if(business!=null){
            if(business.getSelectStatus()==1){
                //已完成的
                list=runfastBusinessService.selectByExampleWithPageable(doExample, pageable);
                total=runfastBusinessService.countByExample(doExample);
            }else if(business.getSelectStatus()==2){
                //待完善
                list=runfastBusinessService.selectByExampleWithPageable(unDoExample, pageable);
                total=runfastBusinessService.countByExample(unDoExample);
            }else if(business.getSelectStatus()==3){
                //近七日
                list=runfastBusinessService.selectByExampleWithPageable(example7, pageable);
                total=runfastBusinessService.countByExample(example7);
            }
        }else{
            //已完成的
            list=runfastBusinessService.selectByExampleWithPageable(doExample, pageable);
            total=runfastBusinessService.countByExample(doExample);
        }
        if(list.size()>0){
            for(RunfastBusiness business1:list){
                setBusiness(business1);
            }
        }
        doTotal=runfastBusinessService.countByExample(doExample);
        unDoTotal=runfastBusinessService.countByExample(unDoExample);
        total7=runfastBusinessService.countByExample(example7);
        map.put("doTotal",doTotal);
        map.put("unDoTotal",unDoTotal);
        map.put("total7",total7);
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

    /**后台数据营业时间，门店分类转换格式返给前端*/
    public void setBusiness(RunfastBusiness business){
        if(business.getStartwork()!=null && business.getEndwork()!=null){
            business.setFirstTime(TimeUtil.getHourAndMinuteToString(business.getStartwork())+","+TimeUtil.getHourAndMinuteToString(business.getEndwork()));
        }
        if(business.getStartwork2()!=null && business.getEndwork2()!=null){
            business.setSecondTime(TimeUtil.getHourAndMinuteToString(business.getStartwork2())+","+TimeUtil.getHourAndMinuteToString(business.getEndwork2()));
        }
        if(business.getStartwork3()!=null && business.getEndwork3()!=null){
            business.setThirdTime(TimeUtil.getHourAndMinuteToString(business.getStartwork3())+","+TimeUtil.getHourAndMinuteToString(business.getEndwork3()));
        }
        if(business.getMainClassId()!=null){
            RunfastBusinessType businessType=runfastBusinessTypeService.selectByPrimaryKey(business.getMainClassId());
            business.setFirstClass(businessType.getParentId()+","+businessType.getId());
            business.setMainClassName(businessType.getName());
        }
        if(business.getSubClassId1()!=null){
            RunfastBusinessType businessType=runfastBusinessTypeService.selectByPrimaryKey(business.getSubClassId1());
            business.setSecondClass(businessType.getParentId()+","+businessType.getId());
            business.setSubClassName1(businessType.getName());
        }
        if(business.getSubClassId2()!=null){
            RunfastBusinessType businessType=runfastBusinessTypeService.selectByPrimaryKey(business.getSubClassId2());
            business.setThirdClass(businessType.getParentId()+","+businessType.getId());
            business.setSubClassName2(businessType.getName());
        }
        //return business;
    }
    /**
     * 商家信息
     */
    @GetMapping("/info")
    public Result info(Integer id){
        if(id==null){return Result.fail(null,"商家id不能为空！");}
        RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(id);
        if(business!=null){
            setBusiness(business);

        }else{return Result.fail(null,"对应的商家不存在！");}
        return Result.ok(null,business);
    }

    /**
     * 保存商家信息
     */
    @PostMapping("/save")
    public Result save(@Validated(RunfastBusiness.GroupA.class) @RequestBody RunfastBusiness business, BindingResult result) throws ParseException{
        Map<Object,Object> map=new HashMap<Object, Object>();
        if(result.hasErrors()){
            return Result.fail(null,result.getFieldError().getDefaultMessage());
        }else{
            RunfastBusinessAccountsExample example=new RunfastBusinessAccountsExample();
            example.createCriteria().andAccountsEqualTo(business.getMobile());
            Integer in=runfastBusinessAccountsService.countByExample(example);
            if(in>0){
                return Result.fail(null,"该号码已经注册过了！");
            }
            WaiMaiRunfastAgentbusiness  agentbusiness =waiMaiRunfastAgentbusinessService.setAgent(business.getAgentid());
            if(agentbusiness!=null){
                business.setAgentid(agentbusiness.getId());
                business.setAgentname(agentbusiness.getName());
            }else{return Result.fail(null,"找不到对应的代理商！");}
            //第一次保存第一步,设置为未完善
            if(business.getId()==null){business.setUndone(true);}
            setbusiness2(business);
            business.setStatusx(1);//商家状态 -1：冻结 其他正常
            business.setStatus(1);//暂停营业
            business.setStatu(0);//商家营业状态默认正常营业
            business.setCreatetime(new Date());
            business.setGoldbusiness(false);
            business.setPriority(false);
            if(business.getMainClassId()!=null){
                RunfastBusinessType  businessType=runfastBusinessTypeService.selectByPrimaryKey(business.getMainClassId());
                if(businessType!=null){
                    business.setSalerange(businessType.getName());
                }else{return Result.fail(null,"找不到对应的分类！");}
            }else{return Result.fail(null,"主营分类不能为空！");}
            runfastBusinessService.insertSelective(business);
            //默认添加一个商家帐号
            RunfastBusinessAccounts accounts = new RunfastBusinessAccounts();
            accounts.setAccounts(business.getMobile());//用商家手机号码做该商家的第一个帐号
            accounts.setName(business.getName());
            accounts.setBusinessid(business.getId());
            accounts.setBusinessname(business.getName());
            accounts.setCreatetime(new Date());
            accounts.setPassword(DigestUtils.md5Hex("123456"));//默认密码
            accounts.setMobile(business.getMobile());
            accounts.setAgentid(business.getAgentid());
            accounts.setIspush(1);
            accounts.setAgentname(business.getAgentname());
            runfastBusinessAccountsService.insertSelective(accounts);
            /**商家品类*/
            if(business.getMainClassId()!=null){
                setBusinessHasType(0,business.getMainClassId(),business.getId());
            }
            if(business.getSubClassId1()!=null){
                setBusinessHasType(1,business.getSubClassId1(),business.getId());
            }
            if(business.getSubClassId2()!=null){
                setBusinessHasType(1,business.getSubClassId2(),business.getId());
            }
            map.put("businessId",business.getId());
        }
        return Result.ok(null,map);
    }

    public void  setBusinessHasType(Integer type,Integer classId,Integer businessId){
        RunfastBusinessType  businessType=runfastBusinessTypeService.selectByPrimaryKey(classId);
        if(businessType!=null){
            RunfastBusinessHasType businessHasType=new RunfastBusinessHasType();
            businessHasType.setFirstid(businessType.getParentId());
            businessHasType.setSecondid(businessType.getId());
            businessHasType.setType(type);
            businessHasType.setBusinessid(businessId);
            runfastBusinessHasTypeService.insert(businessHasType);
        }
    }

    /**
     * 修改商家
     */
    @PostMapping("/update")
    public Result update(@RequestBody RunfastBusiness business) throws ParseException{
        if(business==null){return Result.fail(null,"商家信息不能为空！");}
        setbusiness2(business);
        RunfastBusiness bu=runfastBusinessService.selectByPrimaryKey(business.getId());
        if(business !=null && business.getUpdateFlage()!=null &&  business.getUpdateFlage()==1){
            //第一步修改
               RunfastBusinessAccountsExample example1=new RunfastBusinessAccountsExample();
               example1.createCriteria().andAccountsEqualTo(business.getMobile()).andBusinessidNotEqualTo(business.getId());
               Integer in=runfastBusinessAccountsService.countByExample(example1);
               if(in>0){
                  return Result.fail(null,"该号码已经注册过了！");
               }
               if(business.getAgentid()==null){
                   business.setAgentid(bu.getAgentid());
               }
               WaiMaiRunfastAgentbusiness  agentbusiness =waiMaiRunfastAgentbusinessService.setAgent(business.getAgentid());
               if(agentbusiness!=null){
                  bu.setAgentid(agentbusiness.getId());
                  bu.setAgentname(agentbusiness.getName());
               }else{return Result.fail(null,"找不到对应的代理商！");}
               bu.setName(business.getName());
               bu.setWmMobile(business.getWmMobile());
               bu.setBossName(business.getBossName());
               bu.setMobile(business.getMobile());
               bu.setMainClassId(business.getMainClassId());
               bu.setSubClassId1(business.getSubClassId1());
               bu.setSubClassId2(business.getSubClassId2());
               bu.setStartwork(business.getStartwork());
               bu.setStartwork2(business.getStartwork2());
               bu.setStartwork3(business.getStartwork3());
               bu.setEndwork(business.getEndwork());
               bu.setEndwork2(business.getEndwork2());
               bu.setEndwork3(business.getEndwork3());
               bu.setProvinceId(business.getProvinceId());
               bu.setProvinceName(business.getProvinceName());
               bu.setCityid(business.getCityid());
               bu.setCityname(business.getCityname());
               bu.setCountyid(business.getCountyid());
               bu.setCountyname(business.getCountyname());
               bu.setAddress(business.getAddress());
               bu.setLatitude(business.getLatitude());
               bu.setLongitude(business.getLongitude());
               bu.setFaceImage(business.getFaceImage());
               bu.setInnerImage(business.getInnerImage());
               bu.setImgpath(business.getImgpath());
               bu.setMiniImgpath(business.getMiniImgpath());
               if(business.getMainClassId()!=null){
                   RunfastBusinessType  businessType=runfastBusinessTypeService.selectByPrimaryKey(business.getMainClassId());
                   if(businessType!=null){
                       bu.setSalerange(businessType.getName());
                   }else{return Result.fail(null,"找不到对应的分类！");}
               }else{return Result.fail(null,"主营分类不能为空！");}
            runfastBusinessService.updateByPrimaryKey(bu);
            RunfastBusinessHasTypeExample example=new RunfastBusinessHasTypeExample();
            example.createCriteria().andBusinessidEqualTo(business.getId());
            runfastBusinessHasTypeService.deleteByExample(example);
            /**商家品类*/
            if(business.getMainClassId()!=null){
                setBusinessHasType(0,business.getMainClassId(),business.getId());
            }
            if(business.getSubClassId1()!=null){
                setBusinessHasType(1,business.getSubClassId1(),business.getId());
            }
            if(business.getSubClassId2()!=null){
                setBusinessHasType(1,business.getSubClassId2(),business.getId());
            }
            RunfastBusinessAccountsExample example2=new RunfastBusinessAccountsExample();
            example2.createCriteria().andBusinessidEqualTo(bu.getId());
            List<RunfastBusinessAccounts> accountsList = runfastBusinessAccountsService.selectByExample(example2);
            if(accountsList.size()>0){
                RunfastBusinessAccounts accounts=accountsList.get(0);
                accounts.setAccounts(bu.getMobile());//用商家手机号码做该商家的第一个帐号
                accounts.setName(bu.getName());
                accounts.setBusinessid(bu.getId());
                accounts.setBusinessname(bu.getName());
                accounts.setMobile(bu.getMobile());
                accounts.setAgentid(bu.getAgentid());
                accounts.setIspush(1);
                accounts.setAgentname(bu.getAgentname());
                runfastBusinessAccountsService.updateByPrimaryKeySelective(accounts);
            }
            Map<Object,Object> map=new HashMap<Object, Object>();
            map.put("businessid",bu.getId());
            List<RunfastGoodsSell> goodsSellList=runfastGoodsSellService.selectByMap(map);
            if(goodsSellList.size()>0){
                 for(RunfastGoodsSell goodsSell:goodsSellList){
                     goodsSell.setBusinessname(bu.getName());
                     runfastGoodsSellService.updateByPrimaryKeySelective(goodsSell);
                 }
            }
        }else if(business !=null &&  business.getUpdateFlage()!=null && business.getUpdateFlage()==2){
              //第二部修改
               bu.setMaincert(business.getMaincert());
               bu.setMainimg(business.getMainimg());
               bu.setMainorgname(business.getMainorgname());
               bu.setMainleader(business.getMainleader());
               bu.setRegisternum(business.getRegisternum());
               bu.setRegisteraddress(business.getRegisteraddress());
               bu.setMainexpirationdate(business.getMainexpirationdate());
               bu.setTradecert(business.getTradecert());
               bu.setTradeimg(business.getTradeimg());
               bu.setTradeorgname(business.getTradeorgname());
               bu.setTradeleader(business.getTradeleader());
               bu.setLicensenum(business.getLicensenum());
               bu.setLicenseaddress(business.getLicenseaddress());
               bu.setTradeexpirationdate(business.getTradeexpirationdate());
            runfastBusinessService.updateByPrimaryKey(bu);
        }else if(business !=null &&  business.getUpdateFlage()!=null && business.getUpdateFlage()==3){
              //第三部修改
              WaiMaiRunfastAgentbusiness  agentbusiness =waiMaiRunfastAgentbusinessService.setAgent(bu.getAgentid());
              if(agentbusiness!=null){
                  if(business.getCoefficient()!=null){
                       if(new BigDecimal(business.getCoefficient()).compareTo(agentbusiness.getCoefficient())>0 ){

                       }else{return Result.fail(null,"代理商抽成比例必须大于平台抽成比例!");}
                  }
              }else{return Result.fail(null,"找不到对应的代理商！");}
              bu.setBindingBank(business.getBindingBank());
              bu.setEstablishname(business.getEstablishname());
              bu.setAccount(business.getAccount());
              bu.setBank(business.getBank());
              bu.setIsdeliver(business.getIsdeliver());
              /**抽佣比例大于，平台对代理商的抽佣比例*/
              bu.setCoefficient(business.getCoefficient());
              bu.setPeriod(business.getPeriod());
              bu.setMinmonety(business.getMinmonety());
              bu.setPacktime(business.getPacktime());
              bu.setStartpay(business.getStartpay());
              bu.setSuportself(business.getSuportself());
              bu.setBusshowps(business.getBusshowps());
              bu.setBookable(business.getBookable());
              bu.setBranchname(business.getBranchname());
              bu.setDrawmode(business.getDrawmode());
            runfastBusinessService.updateByPrimaryKey(bu);
        }else{
            if(StringUtils.isNotBlank(business.getName())){
                bu.setName(business.getName());
                bu.setWmMobile(business.getWmMobile());
                bu.setBossName(business.getBossName());
                bu.setMobile(business.getMobile());
                bu.setStartwork(business.getStartwork());
                bu.setStartwork2(business.getStartwork2());
                bu.setStartwork3(business.getStartwork3());
                bu.setEndwork(business.getEndwork());
                bu.setEndwork2(business.getEndwork2());
                bu.setEndwork3(business.getEndwork3());
                bu.setWorktoday(business.getWorktoday());
                bu.setContent(business.getContent());
                runfastBusinessService.updateByPrimaryKey(bu);
                Map<Object,Object> map=new HashMap<Object, Object>();
                map.put("businessid",bu.getId());
                List<RunfastGoodsSell> goodsSellList=runfastGoodsSellService.selectByMap(map);
                if(goodsSellList.size()>0){
                    for(RunfastGoodsSell goodsSell:goodsSellList){
                        goodsSell.setBusinessname(bu.getName());
                        runfastGoodsSellService.updateByPrimaryKeySelective(goodsSell);
                    }
                }
            }else{
                WaiMaiRunfastAgentbusiness  agentbusiness =waiMaiRunfastAgentbusinessService.setAgent(bu.getAgentid());
                if(agentbusiness!=null){
                    if(business.getCoefficient()!=null){
                        if(new BigDecimal(business.getCoefficient()).compareTo(agentbusiness.getCoefficient())>0 ){

                        }else{return Result.fail(null,"代理商抽成比例必须大于平台抽成比例!");}
                    }
                }else{return Result.fail(null,"找不到对应的代理商！");}
                runfastBusinessService.updateByPrimaryKeySelective(business);
            }
        }
        //不是第一次保存第一步
        if(business.getId()!=null){
            RunfastBusiness b=runfastBusinessService.selectByPrimaryKey(business.getId());
            if(b.getBindingBank()!=null && b.getMaincert()!=null && b.getTradecert()!=null ){
                if(b.getBindingBank()==true &&b.getMaincert()==1 && b.getTradecert()==1 ){
                    b.setUndone(false);
                    runfastBusinessService.updateByPrimaryKeySelective(b);
                }else{
                    b.setUndone(true);
                    runfastBusinessService.updateByPrimaryKeySelective(b);
                }
            }else{
                b.setUndone(true);
                runfastBusinessService.updateByPrimaryKeySelective(b);
            }
        }
        return Result.ok(null);
    }

    /**前端传给后台数据转换--营业时间*/
    public void setbusiness2(RunfastBusiness business) throws ParseException{
        if(StringUtils.isNoneBlank(business.getFirstTime())){
            List<String> result = Arrays.asList(StringUtils.split(business.getFirstTime(),","));
            if(result.size()>0){
                business.setStartwork(TimeUtil.getHourAndMinute(result.get(0)));
                business.setEndwork(TimeUtil.getHourAndMinute(result.get(1)));
            }
        }else{
            business.setStartwork(null);
            business.setEndwork(null);
        }
        if(StringUtils.isNoneBlank(business.getSecondTime())){
            List<String> result = Arrays.asList(StringUtils.split(business.getSecondTime(),","));
            if(result.size()>0){
                business.setStartwork2(TimeUtil.getHourAndMinute(result.get(0)));
                business.setEndwork2(TimeUtil.getHourAndMinute(result.get(1)));
            }
        }else{
            business.setStartwork2(null);
            business.setEndwork2(null);
        }
        if(StringUtils.isNoneBlank(business.getThirdTime())){
            List<String> result = Arrays.asList(StringUtils.split(business.getThirdTime(),","));
            if(result.size()>0){
                business.setStartwork3(TimeUtil.getHourAndMinute(result.get(0)));
                business.setEndwork3(TimeUtil.getHourAndMinute(result.get(1)));
            }
        }else{
            business.setStartwork3(null);
            business.setEndwork3(null);
        }
    }
    /**
     * 商户列表查询（因为要链表查询，单独做了一个接口）
     * */
    @GetMapping("/businessList")
    public Result businessList(@PageableDefault Pageable pageable,RunfastBusiness business){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(business.getId() !=null){
            map1.put("id",business.getId());
        }
        if(StringUtils.isNotBlank(business.getName())){
            map1.put("name",business.getName());
        }
        /**是否商家自配送*/
        if(business.getIsdeliver()!=null){
            map1.put("isDeliver",business.getIsdeliver());
        }
        /**是否支持自取*/
        if(business.getSuportself()!=null){//是否支持自取（1：自取）
            map1.put("suportSelf",business.getSuportself());
        }
        /**代理商多选*/
        if(StringUtils.isNotBlank(business.getAgentIds())){
            map1.put("agentIds",business.getAgentIds());
        }

        /**是否有效，非冻结的就有效*/
        if(business.getStatusx()!=null){
            map1.put("statusx",business.getStatusx());
        }

        /**门店品类*/
        if(business.getMainClassId()!=null){
            map1.put("mainClassId",business.getMainClassId());
        }
        /** 商户品质*/
        if(business.getQualityLevel()!=null){
            map1.put("qualityLevel",business.getQualityLevel());
        }
        /**营业状态：暂停营业，正在营业*/
        if(business.getStatus()!=null){
            //status=1暂停营业  =0正常营业
            map1.put("status",business.getStatus());
        }
        /**认证状态*/
        if(business.getAuthenticationStatus()!=null){
            /**认证状态：1，两证已上传、2，两证未上传、3，仅上传部分*/
            map1.put("authenticationStatus",business.getAuthenticationStatus());
        }
        map1.put("pageable",pageable);

        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        if(admin!=null && admin.getType()==3  && accounts!=null){
            //商家帐号登录----只能看自己商家的
            if(business.getId() ==null){
                map1.put("id",accounts.getBusinessid());
            }
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商
            if(StringUtils.isEmpty(business.getAgentIds())){
                map1.put("agentIds",agentAccounts.getAgentid());
            }
        }else if(admin !=null  &&   admin.getType()==1){
            //后台管理员---查看全部的
            if(admin.getAgents().size()>0){
                if(StringUtils.isEmpty(business.getAgentIds())){
                    String  agentIds=Joiner.on(",").join(admin.getAgents());
                    if(StringUtils.isEmpty(business.getAgentIds())){
                        map1.put("agentIds",agentIds);
                    }
                }
            }
        }
        List<RunfastBusiness>  list=runfastBusinessService.selectBusinessByExampleWithPageable(map1);
        Integer total=runfastBusinessService.countBusinessByExample(map1);
        if(list.size()>0){
            for(RunfastBusiness business1:list){
                setBusiness(business1);
                runfastBusinessService.setActivityToBusiness(business1);
            }
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }


    /**
     *商品管理列表
     * */
    @GetMapping("/businessWithGoods")
    public Result businessWithGoods(@PageableDefault Pageable pageable,RunfastBusiness business){

        /**代理商登录，商家登录，后台登录*/
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        //RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(business!=null){
            /**商家名字*/
            if(StringUtils.isNotBlank(business.getName())){
                map1.put("name",business.getName());
            }
            /**门店品类*/
            if(business.getMainClassId()!=null){
                map1.put("mainClassId",business.getMainClassId());
            }
            /**营业状态*/
            if(business.getStatus()!=null){
                map1.put("status",business.getStatus());
            }
        }
        /*  if(admin!=null && admin.getType()==3 && accounts!=null){
            exampleCriteria.andIdEqualTo(accounts.getBusinessid());
        }else*/
        if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            map1.put("agentIds",agentAccounts.getAgentid());
        }else if(admin!=null &&admin.getType()==1){
            if(StringUtils.isNotBlank(business.getAgentIds())){
                map1.put("agentIds",business.getAgentIds());
            }else{
                if(admin.getAgents().size()>0){
                    map1.put("agentIds",Joiner.on(",").join(admin.getAgents()));
                }
            }
        }
        map1.put("pageable",pageable);
        List<RunfastBusiness>  list=runfastBusinessService.selectBusinessWithGoods(map1);
        if(list.size()>0){
             for(RunfastBusiness business1:list){
                 setBusiness(business1);
             }
        }
        Integer total=runfastBusinessService.countByMap(map1);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

    /**
     * 根据商家id，及查询条件，进入对应的商家页面
     * */
    @GetMapping("/findByBusinessId")
    public Result findByBusinessId(RunfastGoodsSell goodsSell1){
        if(goodsSell1.getBusinessid()==null){return Result.fail(null,"商户id不能为空！");}
        RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(goodsSell1.getBusinessid());
        if(business==null){return Result.fail(null,"没找到对应的商家！");}
        List<RunfastGoodsSellType> typeList=new ArrayList<RunfastGoodsSellType>();
        if(business !=null){
            Map<Object,Object> map1=new HashMap<Object, Object>();
            map1.put("businessId",business.getId());
            map1.put("agentId",business.getAgentid());
            typeList=runfastGoodsSellTypeService.selectByMap(map1);
        }
        Integer total=0;
        List<RunfastGoodsSellType> list=new ArrayList<RunfastGoodsSellType>();
        /**在售库存充足的商品，库存低于10的商品，已经下架的商品，价格异常的商品（金额高于200元，打包盒高于5元），已经被删除的商品*/
        Map<Object,Object> map2=new HashMap<Object, Object>();
        map2.put("businessid",business.getId());
        map2.put("agentIds",business.getAgentid());
        List<RunfastGoodsSell> adequateGoodsSellList1=runfastGoodsSellService.selectByMap(map2);
        List<RunfastGoodsSell> adequateGoodsSellList=runfastGoodsSellService.setStandardListAndOptionList(adequateGoodsSellList1);
        /**/
        //遍历删除,除去男生
        /*Iterator<Student> iterator = list.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            if ("male".equals(student.getGender())) {
                iterator.remove();//使用迭代器的删除方法删除
            }
        }*/
        Iterator<RunfastGoodsSell> iterator=adequateGoodsSellList.iterator();
        while (iterator.hasNext()){
            RunfastGoodsSell  goodsSell=iterator.next();
            if(goodsSell.getStandardList().size()>0){
                for(RunfastGoodsSellStandard standard:goodsSell.getStandardList()){
                    if(standard.getNum()<10){
                        iterator.remove();
                        break;
                    }
                    if(standard.getPrice()>200){
                        iterator.remove();
                        break;
                    }
                    if(standard.getPackageFee()>5){
                        iterator.remove();
                        break;
                    }

                }
            }
        }
        Integer adequateTotal=adequateGoodsSellList.size();
        /**库存低于10的商品*/
        List<RunfastGoodsSell> shortGoodsSellList=new ArrayList<RunfastGoodsSell>();
        RunfastGoodsSellExample goodsSellExample2=new RunfastGoodsSellExample();
        goodsSellExample2.createCriteria().andBusinessidEqualTo(business.getId()).andAgentidEqualTo(business.getAgentid()).andStatusEqualTo(0).andDeletedNotEqualTo(1);
        goodsSellExample2.setOrderByClause("sort asc");
        List<RunfastGoodsSell> shortGoodsSellList11=runfastGoodsSellService.selectByExample(goodsSellExample2);
        List<RunfastGoodsSell> shortGoodsSellList1=runfastGoodsSellService.setStandardListAndOptionList(shortGoodsSellList11);
        if(shortGoodsSellList1.size()>0){
            for(RunfastGoodsSell  goodsSell:shortGoodsSellList1){
                    if(goodsSell.getStandardList().size()>0){
                        for(RunfastGoodsSellStandard standard:goodsSell.getStandardList()){
                            if(standard.getNum()<10){
                                shortGoodsSellList.add(goodsSell);
                                break;
                            }
                        }
                    }
            }
        }
        Integer shortTotal=shortGoodsSellList.size();
        /**已经下架的商品*/
        RunfastGoodsSellExample goodsSellExample3=new RunfastGoodsSellExample();
        goodsSellExample3.createCriteria().andBusinessidEqualTo(business.getId()).andAgentidEqualTo(business.getAgentid()).andStatusEqualTo(2).andDeletedNotEqualTo(1);//状态 0正常销售 1：暂停销售 2：商品下架//是否已经被删除
        Integer dropOffTotal=runfastGoodsSellService.countByExample(goodsSellExample3);
        /**价格异常的商品（金额高于200元，打包盒高于5元）*/
        List<RunfastGoodsSell> abnormalGoodsSellList=new ArrayList<RunfastGoodsSell>();
        RunfastGoodsSellExample goodsSellExample4=new RunfastGoodsSellExample();
        goodsSellExample4.createCriteria().andBusinessidEqualTo(business.getId()).andAgentidEqualTo(business.getAgentid()).andStatusEqualTo(0).andDeletedNotEqualTo(1);//是否已经被删除
        goodsSellExample4.setOrderByClause("sort asc");
        //打包盒高于5元
        List<RunfastGoodsSell> abnormalGoodsSellList11=runfastGoodsSellService.selectByExample(goodsSellExample4);
        List<RunfastGoodsSell> abnormalGoodsSellList1=runfastGoodsSellService.setStandardListAndOptionList(abnormalGoodsSellList11);
        if(abnormalGoodsSellList1.size()>0){
            for(RunfastGoodsSell  goodsSell:abnormalGoodsSellList1){
                if(goodsSell.getStandardList().size()>0){
                    for(RunfastGoodsSellStandard standard:goodsSell.getStandardList()){
                        if(standard.getPrice()>200){
                            abnormalGoodsSellList.add(goodsSell);
                            break;
                        }
                        if(standard.getPackageFee()>5){
                            abnormalGoodsSellList.add(goodsSell);
                            break;
                        }
                    }
                }
            }
        }
        Integer abnormalTotal=abnormalGoodsSellList.size();
        /**已经被删除的商品*/
        RunfastGoodsSellExample goodsSellExample5=new RunfastGoodsSellExample();
        goodsSellExample5.createCriteria().andBusinessidEqualTo(business.getId()).andDeletedEqualTo(1).andAgentidEqualTo(business.getAgentid());//0未被删除，1已删除
        Integer deleteTotal=runfastGoodsSellService.countByExample(goodsSellExample5);
        if(goodsSell1!=null){
            if(goodsSell1.getSelectStatus()!=null){
                if(goodsSell1.getSelectStatus()==1){
                    // 在售库存充足的商品-----菜单商品
                    //list=adequateGoodsSellList;
                    list=setGoodsToType(typeList,adequateGoodsSellList);
                    total=adequateGoodsSellList.size();
                }else if(goodsSell1.getSelectStatus()==2){
                    //库存不足商品
                    //list=shortGoodsSellList;
                    list=setGoodsToType(typeList,shortGoodsSellList);
                    total=shortGoodsSellList.size();
                }else if(goodsSell1.getSelectStatus()==3){
                    //已下架
                    goodsSellExample3.setOrderByClause("sort asc");
                    List<RunfastGoodsSell> dropOffGoodsSellList1=runfastGoodsSellService.selectByExample(goodsSellExample3);
                    List<RunfastGoodsSell> dropOffGoodsSellList=runfastGoodsSellService.setStandardListAndOptionList(dropOffGoodsSellList1);
                    list=setGoodsToType(typeList,dropOffGoodsSellList);
                    total=runfastGoodsSellService.countByExample(goodsSellExample3);
                }else if(goodsSell1.getSelectStatus()==4){
                    //价格异常
                    list=setGoodsToType(typeList,abnormalGoodsSellList);
                    total=abnormalGoodsSellList.size();
                }else if(goodsSell1.getSelectStatus()==5){
                    //回收站
                    goodsSellExample5.setOrderByClause("sort asc");
                    List<RunfastGoodsSell> deleteGoodsSellList1=runfastGoodsSellService.selectByExample(goodsSellExample5);
                    List<RunfastGoodsSell> deleteGoodsSellList2=runfastGoodsSellService.setStandardList(deleteGoodsSellList1);
                    List<RunfastGoodsSell> deleteGoodsSellList=runfastGoodsSellService.setOptionList(deleteGoodsSellList2);
                   // List<RunfastGoodsSell> deleteGoodsSellList=runfastGoodsSellService.setStandardListAndOptionList(deleteGoodsSellList1);
                    list=setGoodsToType(typeList,deleteGoodsSellList);
                    total=runfastGoodsSellService.countByExample(goodsSellExample5);
                }
            }else{
                //默认展示的
                list=setGoodsToType(typeList,adequateGoodsSellList);
                total=adequateGoodsSellList.size();
            }
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("adequateTotal",adequateTotal);
        map.put("shortTotal",shortTotal);
        map.put("dropOffTotal",dropOffTotal);
        map.put("abnormalTotal",abnormalTotal);
        map.put("deleteTotal",deleteTotal);
        map.put("list",list);
        map.put("total",total);
        return  Result.ok(null,map);
    }

    /**把商品放入对应的类型里*/
    private List<RunfastGoodsSellType> setGoodsToType( List<RunfastGoodsSellType> typeList,List<RunfastGoodsSell> list){
        if(typeList.size()>0){
            for(RunfastGoodsSellType type:typeList){
                List<RunfastGoodsSell> goodsSellList=new ArrayList<RunfastGoodsSell>();
                if(list.size()>0){
                    for(RunfastGoodsSell goodsSell:list){
                         if(goodsSell.getSelltypeid().equals(type.getId())){
                             goodsSellList.add(goodsSell);
                         }
                    }
                }
                type.setNum(goodsSellList.size());
                type.setGoodsSells(goodsSellList);
               /* if(type.getNum()==0){
                    typeList.remove(type);
                }*/
            }
        }
      return typeList;
    }


    /**
     * 根据活动id，进入对应的商家页面--单品活动使用的
     * */
    @GetMapping("/setActivityToGoodssellStandard")
    public Result setActivityToGoodssellStandard(Integer activityId,String name){
        Map<Object,Object> map=new HashMap<Object, Object>();
        if(activityId!=null){
            RunfastActivity activity=runfastActivityService.selectByPrimaryKey(activityId);
            if(activity!=null){
                RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(activity.getBusid());
                if(business==null){return Result.fail(null,"没找到对应的商家！");}
                List<RunfastGoodsSellType> typeList=new ArrayList<RunfastGoodsSellType>();
                if(business !=null){
                    RunfastGoodsSellTypeExample example=new RunfastGoodsSellTypeExample();
                    example.createCriteria().andBusinessidEqualTo(business.getId()).andDeletedNotEqualTo(1).andAgentidEqualTo(business.getAgentid());
                    example.setOrderByClause("sort asc");
                    typeList=runfastGoodsSellTypeService.selectByExample(example);
                }
                Integer total=0;
                List<RunfastGoodsSellType> list=new ArrayList<RunfastGoodsSellType>();
                /**在售的商品*/
                Map<Object,Object> map1=new HashMap<Object, Object>();
                map1.put("businessid",business.getId());
                map1.put("agentIds",business.getAgentid());
                List<RunfastGoodsSell> list1=runfastGoodsSellService.selectByMap(map1);
                List<RunfastGoodsSell> list2=runfastGoodsSellService.setStandardListAndOptionList(list1);
                list=setGoodsToType(typeList,list2);
                total=list.size();
                map.put("list",list);
                map.put("total",total);
            }
        }
        return  Result.ok(null,map);
    }


}
